<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>密码框验证消息</title>
    <style>
      .box {
        width: 600px;
        margin: 100px auto 0;
      }

      .box .xing {
        margin-right: 5px;
        color: red;
        font-weight: bold;
      }

      .box > .password {
        outline: none;
      }

      .box > .desc-box {
        display: inline-block;
        margin-left: 5px;
      }
      .box > .desc-box > img {
        vertical-align: middle;
      }
      .box > .desc-box > span {
        color: #999999;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <label><span class="xing">*</span>设置密码：</label>
      <input type="password" class="password" />
      <div class="desc-box">
        <img src="./imgs/desc.png" class="img" />
        <span class="desc">请输入6~16位密码</span>
      </div>
    </div>

    <script>
      var inputEle = document.querySelector('.password');
      var img = document.querySelector('.img');
      var desc = document.querySelector('.desc');

      // 失去焦点
      inputEle.onblur = function () {
        // 判断是否输入内容
        if (this.value.length === 0) {
          img.src = './imgs/error.png';
          desc.innerHTML = '请输入密码';
          desc.style.color = 'red';
        } else {
          if (this.value.length < 6 || this.value.length > 16) {
            img.src = './imgs/error.png';
            desc.innerHTML = '输入的位数不正确';
            desc.style.color = 'red';
          } else {
            img.src = './imgs/correct.png';
            desc.innerHTML = '您输入正确';
            desc.style.color = 'green';
          }
        }
      };

      // 获得焦点
      inputEle.onfocus = function () {
        img.src = './imgs/desc.png';
        desc.innerHTML = '请输入6~16位密码';
        desc.style.color = '#999999';
      };
    </script>
  </body>
</html>
